<template>
    <div class="g-container">
        <div class="g-wrapper">
            <!-- v-color="'pink'" -->
            <h2>管理员登录</h2>
            <el-form
                class="g-login"
                :rules="rules"
                :model="user"
                ref="loginFormRef"
            >
                <el-form-item prop="name">
                    <el-input placeholder="请输入用户名" v-model="user.name">
                        <template #prefix>
                            <el-icon><User /></el-icon>
                        </template>
                    </el-input>
                </el-form-item>
                <el-form-item prop="password">
                    <el-input
                        placeholder="请输入密码"
                        v-model="user.password"
                        show-password
                    >
                        <template #prefix>
                            <el-icon><Lock /></el-icon>
                        </template>
                    </el-input>
                </el-form-item>
                <el-form-item prop="spassword">
                    <el-input
                        placeholder="请再次输入密码"
                        v-model="user.spassword"
                        show-password
                    >
                        <template #prefix>
                            <el-icon><Lock /></el-icon>
                        </template>
                    </el-input>
                </el-form-item>
                <el-form-item prop="Inum" v-if="identifyState">
                    <el-input
                        placeholder="请输入验证吗"
                        v-model="user.Inum"
                    >
                        <template #suffix>
                            <Identify :identifyCode="identifyCode" @click="refreshCode" />
                        </template>
                    </el-input>
                </el-form-item>
                <el-checkbox v-model="checked1" label="记住密码" size="large" />
                <el-button type="primary" @click="bindLogin">登录</el-button>
            </el-form>
            <!-- <button @click="testFn">测试</button> -->
            <!-- {{ menuList }} -->
        </div>
    </div>
</template>

<script lang="ts" setup>
import axios from 'axios'
import { User, Lock } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { onMounted, ref } from 'vue'
import { useAccountStore } from '@/stores/user'
import { useRouter } from 'vue-router'
import Identify from '@/components/Verification.vue'
import {sha256} from 'js-sha256'

import { useMenuStore } from '@/stores/menu'
import { computed } from 'vue'
import { number } from 'echarts'
const menuStore = useMenuStore()
const menuList = computed(() => menuStore.list) //动态菜单数据

// 记住密码
const checked1 = ref('') // ture / false
const SavePss = ()=>{
    const accountStore = useAccountStore()
    if(accountStore.account2){
        let { username, password } = accountStore.account2
        // password = sha256(password)
        user.value.name = username?username:''
        user.value.password = password?password:''
        user.value.spassword = password?password:''
    }
}


// 测试验证码
const testFn = ()=>{
    // 动态权限菜单
    // menuStore.saveMenuList(1)
    // console.log('menuList>>>',menuList)
    // console.log('menuStore.list>>>',menuStore.list)

    // 加密
    let number = 'zxczxc123' 
    number = sha256(number)
    console.log(number);
    
}

const router = useRouter()

const user = ref({
    name: '',
    password: '',
    spassword: '',
    Inum: '',
})
/**
 * 确定密码方法
 */
 const validatePass2 = (rule: any, value: any, callback: any) => {
    if (value === '') {
        callback(new Error('请输入再次密码'))
    } else if (value !== user.value.password) {
        callback(new Error('两次输入密码不匹配!'))
    } else {
        callback()
    }
}


// 定义校验规则,在data选项中,
// 在form-item中使用prop绑定规则
// 双向数据绑定 v-model
// form单表中使用 :model="user"
const rules = {
    name: [
        {
            required: true,
            message: '请输入用户名',
            trigger: 'blur',
        },
    ],
    password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
    spassword: [{ validator:validatePass2, trigger: 'blur' }],
    Inum: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
}

const loginFormRef = ref()

const bindLogin = async () => {
    const accountStore = useAccountStore()
    const { name, password } = user.value
    const formRef = loginFormRef.value
    formRef.validate(async valid => {
        // 1. 表单校验
        if (valid) {
            if(count.value >= 3){
                identifyState.value = true
                if(user.value.Inum != identifyCode.value){
                ElMessage({
                    message: '验证码错误!',
                    type: 'error',
                    })
                    refreshCode()
                    return
                }
            }
            // 2. 调用登录接口，验证账户
            const data = await axios({
                method: 'post',
                url: 'http://localhost:3000/operator/login',
                //post请求参数使用data选项, get参数 params选项
                data: {
                    username: name,
                    password:sha256(password),
                },
            })
            // console.log(data)
            const { code, info, token } = data.data
            // console.log("info>>>",info);

            if (code === 1) {
                // 记住密码
                if(checked1.value) accountStore.saveAccount2({username:name,password})
                

                // 3. 保存用户昵称和头像，用于主界面显示
                // const userInfo = {
                //     nick: info.nick,
                // }
                accountStore.saveAccount(info)
                // $store.dispatch('account/saveAccount',userInfo)

                // 4. 保存token
                localStorage.setItem('TOKEN', token)
                localStorage.setItem('ROLEID', info.role_id)
                // 5. 跳转到主界
                ElMessage({
                    message: '登录成功!',
                    type: 'success',
                })
                // 6. 
                menuStore.saveMenuList(info.role_id)

                router.push({ path: '/home' })
            } else {
                ElMessage({
                    message: '账号出错!',
                    type: 'error',
                })
                count.value ++
            }
        }
    })
}

// 验证码业务
const identifyCode = ref();
const identifyCodes = ref("1234567890abcdefjhijklinopqrsduvwxyz");

// 验证码组件是否渲染
const identifyState = ref(false)

let count = ref<number>(0) //记录三次出错显示验证码
 
// 重置验证码
const refreshCode = () => {
	identifyCode.value = "";
	makeCode(identifyCode, 4);
};

 
const makeCode = (o: any, l: number) => {
	for (let i = 0; i < l; i++) {
		identifyCode.value += identifyCodes.value[randomNum(0, identifyCodes.value.length)];
	}
};
 
 
const randomNum = (min: number, max: number) => {
	return Math.floor(Math.random() * (max - min) + min);
};

onMounted(() => {
    SavePss()
    refreshCode()
})

</script>

<style lang="scss" scoped>
.g-container {
    width: 100%;
    height: 100vh;
    background-color: #2b3c4d;
    background-image: url(../assets/img/7509f45a34dfebba021e9ecc8027386f.jpeg);
    background-size: 100%;
    position: relative;
    .g-wrapper {
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
        width: 400px;
        h2 {
            text-align: center;
            color: white;
            margin-bottom: 20px;
        }
        .g-login {
            background-color: white;
            border-radius: 5px;
            padding: 40px 30px;
            .el-button {
                width: 100%;
            }
        }
    }
}
</style>
